var container;
var body;
var reportQueries = new Array();
var variables = new Array();







function getMonthName(i) {
	switch (i) {
		case 12: return "December";
		case 11: return "November";
		case 10: return "October";
		case 9:  return "September";
		case 8:  return "August";
		case 7:  return "June";
		case 6:  return "July";
		case 5:  return "May";
		case 4:  return "April";
		case 3:  return "March";
		case 2:  return "Febuary";
		case 1:  return "January";
		default: return "";
	}
}


function renderDateSelector(parent) {

	var yearSelector = document.createElement("select");
	for (var i=2008; i>2002; i--) {
		yearSelector.options[yearSelector.options.length] = new Option(i, i);
	}
	parent.appendChild(yearSelector);

	var monthSelector = document.createElement("select");
	for (var i=12; i>0; i--) {
		monthSelector.options[monthSelector.options.length] = new Option(getMonthName(i), i);
	}
	parent.appendChild(monthSelector);

	var daySelector = document.createElement("select");
	for (var i=31; i>0; i--) {
		daySelector.options[daySelector.options.length] = new Option(i, i);
	}
	parent.appendChild(daySelector);

}



function renderAdd(parent, clickHandler) {
	var addDiv 	= document.createElement("div");
	addDiv.style.width 	= "100%";
	addDiv.style.textAlign 	= "left";

	var addHref 	= document.createElement("a");
	addHref.href	= "javascript:;";
	var addSymbol 	= document.createElement("img");
	addSymbol.src = "img/silk/add.png";
	addSymbol.style.border = "0px";
	addHref.appendChild(addSymbol);
	addHref.appendChild(document.createTextNode(" add"));
	addDiv.appendChild(addHref);
	parent.appendChild(addDiv);

	Event.observe(addHref, "click", clickHandler);
}

function renderRemove(parent, clickHandler) {
	var removeHref   = document.createElement("a");
	removeHref.href	 = "javascript:;";
	var removeSymbol = document.createElement("img");
	removeSymbol.src = "img/silk/delete.png";
	removeSymbol.style.border = "0px";
	removeHref.appendChild(removeSymbol);
	parent.appendChild(removeHref);

	Event.observe(removeHref, "click", clickHandler);
}




// ---------------------------------
// Primitive functions
// ---------------------------------
function addPrimitive(parent, removable, initValue) {
	var container = document.createElement("div");

	var input = document.createElement("input");
	input.type = "text";
	container.appendChild(input);

	if (initValue) {
		input.value = initValue;
	}

	parent.appendChild(container);

	if (removable) {
		renderRemove(container, removePrimitiveClick);
	}

	return container;
}
function addPrimitiveClick(evt) {
	var elm = Event.findElement(evt);
	var tdElm = elm.parentNode.parentNode;

	var typeContainer = addPrimitive(tdElm, true, null);
	var paramName = tdElm.getAttribute("name");

	var rq = getReportQueryFromElement(elm);
	rq.addParamHandle(paramName, typeContainer);
}
function removePrimitiveClick(evt) {
	var elm = Event.findElement(evt);
	var tdElm = elm.parentNode.parentNode.parentNode;
	var typeContainer = elm.parentNode.parentNode;

	var paramName = tdElm.getAttribute("name");

	var rq = getReportQueryFromElement(elm);
	rq.removeParamHandle(paramName, typeContainer);

	tdElm.removeChild(typeContainer);
}
function getPrimitiveString(container) {
	return container.firstChild.value;
}



// ---------------------------------
// Date Range functions
// ---------------------------------
function addDateRange(parent, removable, initValue) {
	var container = document.createElement("div");
	renderDateSelector(container);
	container.appendChild(document.createTextNode(" to "));
	renderDateSelector(container);
	parent.appendChild(container);

	if (initValue) {
		setDateRangeValue(container, initValue);
	}

	if (removable) {
		renderRemove(container, removeDateRangeClick);
	}

	return container;
}
function addDateRangeClick(evt) {
	var elm = Event.findElement(evt);
	var tdElm = elm.parentNode.parentNode;

	var typeContainer = addDateRange(tdElm, true, null);
	var paramName = tdElm.getAttribute("name");

	var rq = getReportQueryFromElement(elm);
	rq.addParamHandle(paramName, typeContainer);
}
function removeDateRangeClick(evt) {
	var elm = Event.findElement(evt);
	var tdElm = elm.parentNode.parentNode.parentNode;
	var typeContainer = elm.parentNode.parentNode;

	var paramName = tdElm.getAttribute("name");

	var rq = getReportQueryFromElement(elm);
	rq.removeParamHandle(paramName, typeContainer);

	tdElm.removeChild(typeContainer);
}
function getDateRangeString(container) {
	var fieldCount	= 0;
	var date1String = "";
	var date2String = "";
	for (var j=0; j<container.childNodes.length; j++) {
		if (container.childNodes[j].nodeName.toLowerCase() == "select") {
			var selector = container.childNodes[j];

			if (fieldCount < 3) {
				if (date1String != "")
					date1String += "-";
				date1String += selector.options[selector.options.selectedIndex].value;
			} else {
				if (date2String != "")
					date2String += "-";
				date2String += selector.options[selector.options.selectedIndex].value;
			}

			fieldCount++;
		}
	}

	return date1String+" to "+date2String;
}
function setDateRangeValue(container, datesString) {
	var dates = datesString.split("to");
	if (dates.length == 2) {
		var date1 = dates[0].trim().split("-");
		var date2 = dates[1].trim().split("-");

		if ( (date1.length == 3) && (date2.length == 3) ) {
			var y1 = date1[0];
			var m1 = date1[1];
			var d1 = date1[2];

			var y2 = date2[0];
			var m2 = date2[1];
			var d2 = date2[2];

			var fieldCount  = 0;
			for (var j=0; j<container.childNodes.length; j++) {
				if (container.childNodes[j].nodeName.toLowerCase() == "select") {
					var selector = container.childNodes[j];

					var val = -1;
					switch (fieldCount) {
						case 0:	val = y1; break;
						case 1:	val = m1; break;
						case 2:	val = d1; break;

						case 3:	val = y2; break;
						case 4:	val = m2; break;
						case 5:	val = d2; break;
					}

					selectOption(selector, val);

					fieldCount++;
				}
			}
		}
	}
}


// ---------------------------------
// Date functions
// ---------------------------------
function addDate(parent, removable, initValue) {
	var container = document.createElement("div");
	renderDateSelector(container);
	parent.appendChild(container);

	if (initValue) {
		setDateValue(container, initValue);
	}

	if (removable) {
		renderRemove(container, removeDateClick);
	}

	return container;
}
function addDateClick(evt) {
	var elm = Event.findElement(evt);
	var tdElm = elm.parentNode.parentNode;

	var typeContainer = addDate(tdElm, true, null);
	var paramName = tdElm.getAttribute("name");

	var rq = getReportQueryFromElement(elm);
	rq.addParamHandle(paramName, typeContainer);

}
function removeDateClick(evt) {
	var elm = Event.findElement(evt);
	var tdElm = elm.parentNode.parentNode.parentNode;
	var typeContainer = elm.parentNode.parentNode;

	var paramName = tdElm.getAttribute("name");

	var rq = getReportQueryFromElement(elm);
	rq.removeParamHandle(paramName, typeContainer);

	tdElm.removeChild(typeContainer);
}
function getDateString(container) {
	var dateString = "";
	for (var j=0; j<container.childNodes.length; j++) {
		if (container.childNodes[j].nodeName.toLowerCase() == "select") {
			var selector = container.childNodes[j];

			if (dateString != "")
				dateString += "-";
			dateString += selector.options[selector.options.selectedIndex].value;
		}
	}

	return dateString;
}
function setDateValue(container, dateStr) {

	var date1 = dateStr.split("-");

	if (date1.length == 3) {
		var y1 = date1[0];
		var m1 = date1[1];
		var d1 = date1[2];

		var fieldCount  = 0;
		for (var j=0; j<container.childNodes.length; j++) {
			if (container.childNodes[j].nodeName.toLowerCase() == "select") {
				var selector = container.childNodes[j];

				var val = -1;
				switch (fieldCount) {
					case 0:	val = y1; break;
					case 1:	val = m1; break;
					case 2:	val = d1; break;
				}

				selectOption(selector, val);

				fieldCount++;
			}
		}
	}
}



function createQuerySelector() {

	//Container
	var ator = document.createElement("div");
	ator.style.textAlign = "right";

	//Select
	var querySelector = document.createElement("select");
	querySelector.setAttribute("id", "querySelector");

	for (var i=0; i<queries.length; i++) {
		querySelector.options[querySelector.options.length] = new Option(queries[i].title, queries[i].title);
	}

	//Submit button
	var submitButton = document.createElement("input");
	submitButton.setAttribute("type", "submit");
	submitButton.setAttribute("value", "Add to report");

	ator.appendChild(querySelector);
	ator.appendChild(submitButton);
	container.appendChild(ator);

	Event.observe(submitButton, "click", addQueryClick);
}

function createBasicInformationInput() {

	var container = document.createElement("div");
	container.className = "content_table";

	//Render title
	var titleElm = document.createElement("h3");
	titleElm.appendChild(document.createTextNode("Basic Information"));
	titleElm.className = "table_header";

	//Render inputs
	var table = document.createElement("table");
	table.style.width = "100%";
	var tbody = document.createElement("tbody");



	//Add 'title' input
	var tr = document.createElement("tr");
	var tdName = document.createElement("td");
	tdName.vAlign = "top"
	var tdData = document.createElement("td");

	tdName.appendChild(document.createTextNode("Title"));
	var input = document.createElement("input");
	input.type = "text";
	input.style.width = "100%";
	input.setAttribute("id", "report_title");
	tdData.appendChild(input);

	tr.appendChild(tdName);
	tr.appendChild(tdData);
	tbody.appendChild(tr);



	//Add 'description' input
	var tr = document.createElement("tr");
	var tdName = document.createElement("td");
	tdName.vAlign = "top"
	var tdData = document.createElement("td");

	tdName.appendChild(document.createTextNode("Description"));
	var input = document.createElement("textarea");
	input.style.width = "100%";
	input.setAttribute("id", "report_description");
	tdData.appendChild(input);

	tr.appendChild(tdName);
	tr.appendChild(tdData);
	tbody.appendChild(tr);




	container.appendChild(titleElm);
	table.appendChild(tbody);
	container.appendChild(table);
	$("report_container").appendChild(container);
}







function saveTemplate(evt) {

	var reportTitle 	= $("report_title").value;
	var reportDescription 	= $("report_description").value;
	if (reportTitle == "") {
		showError("Title cannot be empty");
		return;
	}

	var xml  = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
	xml += "<template title=\""+reportTitle+"\">\n";

	xml += "\t<meta>\n";
	xml += "\t\t<description>\n";
	xml += "\t\t\t"+reportDescription.replace(/\n/g, " ")+"\n";
	xml += "\t\t</description>\n";
	xml += "\t</meta>\n";

	xml += "\t<variables>\n";
	for (var i=0; i<variables.length; i++) {
		xml += variables[i].toXML("\t\t");
	}
	xml += "\t</variables>\n";

	for (var i=0; i<reportQueries.length; i++) {
		xml += reportQueries[i].toXML("\t");
	}

	xml += "</template>\n";


	new Ajax.Request("api_save_template.php", {
		method: 'post',
		contentType: "text/xml",
		postBody: xml,
		onSuccess: function(transport) {
			showMessage("Report template was successfully saved!");
		},
		onFailure: function(transport) {
		},
	});
}


function loadTemplate(filename) {

	new Ajax.Request("api_load_template.php?file="+filename, {
		method: 'get',
		onSuccess: function(transport) {
			renderTemplate(transport.responseXML);
		},
		onFailure: function(transport) {
		},
	});

}


function renderTemplate(xml) {

	var reportNode = xml.getElementsByTagName("template").item(0);

	//Set title
	$("report_title").value = reportNode.getAttribute("title");

	//Set description
	$("report_description").value = reportNode.getElementsByTagName("meta").item(0).getElementsByTagName("description").item(0).firstChild.nodeValue.trim();


	//Parse queries
	var queries = reportNode.getElementsByTagName("query");
	for (var i=0; i<queries.length; i++) {

		var queryTitle = queries[i].getAttribute("title");
		addQuery(queryTitle);

		var rq = getReportQueryByTitle(queryTitle);

		//Parse query parameters
		var params = queries[i].getElementsByTagName("param");
		for (var p=0; p<params.length; p++) {
			var paramName = params[p].getAttribute("name");
			var paramType = params[p].getAttribute("type");

			//Construct array of values
			var valueArr = new Array();
			var values = params[p].getElementsByTagName("value");
			for (var v=0; v<values.length; v++) {
				valueArr.push(values[v].firstChild.nodeValue.trim());
			}

			rq.setParam(paramName, valueArr);
		}
	}



	//Parse variables
	var vars = reportNode.getElementsByTagName("variable");
	for (var i=0; i<vars.length; i++) {
		var variableName      	= vars[i].getAttribute("name");
		var variableTypeLabel 	= vars[i].getAttribute("type");
		var variableTypeName 	= getTypeDisplayNameFromLabel(variableTypeLabel);
		if (!variableTypeName) {
			variableTypeName = "("+variableTypeLabel+")";  //Assume enumerable
		}

		var defVal 	= null;
		var usesMacro 	= false;

		if (vars[i].getAttribute("uses-macro")) {
			usesMacro = vars[i].getAttribute("uses-macro");
		} else {
			defVal = vars[i].firstChild.nodeValue.trim();
		}

		addVariable(variableName, variableTypeName, defVal, usesMacro);
	}



	resetQueryLoadedStatus();

	//Set variables for queries
	for (var i=0; i<queries.length; i++) {

		var queryTitle = queries[i].getAttribute("title");
		var rq = getReportQueryByTitle(queryTitle);

		//Parse query parameters
		var params = queries[i].getElementsByTagName("param");
		for (var p=0; p<params.length; p++) {

			var paramName = params[p].getAttribute("name");
			var paramType = params[p].getAttribute("type");

			var valueArr = new Array();
			var values = params[p].getElementsByTagName("value");

			for (var v=0; v<values.length; v++) {
				var varAttrib = values[v].getAttribute("uses-variable");
				if (varAttrib) {
					valueArr.push(varAttrib);
				} else {
					valueArr.push(null);
				}
			}

			rq.setVariables(paramName, valueArr);
		}
	}


}


onload = function() {

	body = document.getElementsByTagName("body").item(0);
	container = $("main_container");

	createQuerySelector();

	var reportContainer = document.createElement("div");
	reportContainer.setAttribute("id", "report_container");
	container.appendChild(reportContainer);

	createBasicInformationInput();

	initVariables();



	var footerDiv = document.createElement("div");
	footerDiv.style.width 		= "100%";
	footerDiv.style.textAlign 	= "right";

	var saveHref = document.createElement("a");
	saveHref.href = "javascript:;";
	var saveImg = document.createElement("img");
	saveImg.src = "img/silk/database_save.png";
	saveImg.style.border = "0px";
	saveImg.style.marginRight = "6px";
	saveHref.appendChild(saveImg);
	saveHref.appendChild(document.createTextNode("Save"));
	footerDiv.appendChild(saveHref);

	container.appendChild(footerDiv);
	Event.observe(saveHref, "click", saveTemplate);



	//Has a previous template been requested?
	var paramName = "&template=";
	var paramIdx  = location.href.indexOf(paramName);
	if (paramIdx != -1) {
		var nextParamStart = location.href.indexOf("&", paramIdx+1);
		var paramStop = ( (nextParamStart==-1) ? location.href.length : nextParamStart);
		var paramValue = location.href.substring(paramIdx+paramName.length, paramStop);
		loadTemplate(paramValue);
	}


}

